package com.xinjixian.webgame;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;

public class DownloadUtils {
    private Context mContext;
    private static DownloadUtils utils;

    private DownloadUtils(Context context) {
        mContext = context;
    }

    public static DownloadUtils getExample(Context context) {
        if (utils == null)
            utils = new DownloadUtils(context);
        return utils;
    }

    public void downloadApk() {
        ApkDetail detail = ApkDetail.getData();
        Log.e("12456", "downloadApk");
        if (detail.getStatus().equals("打开") && !APPUtil.isAPPInstalled(mContext, detail.getApkPageName())) {
            Log.e("12456", "downloadApk 下载");
            detail.setState("下载");
        } else if (detail.getStatus().equals("打开") || detail.getStatus().equals("安装")) {
            Log.e("12456", "detail.getStatus()  " + detail.getStatus());
            return;
        }
        if (isWiFiConneted(mContext)) {
            nextDownload(detail);
        }
    }

    private void nextDownload(ApkDetail mGameDetail) {

        if (!HiPermission.checkPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            //申请WRITE_EXTERNAL_STORAGE权限
            List<PermissionItem> permissonItems = new ArrayList<PermissionItem>();
            permissonItems.add(new PermissionItem(Manifest.permission.READ_EXTERNAL_STORAGE, "读取存储卡", R.drawable.permission_ic_storage));
            permissonItems.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "写存储卡", R.drawable.permission_ic_storage));
            HiPermission.create(mContext)
                    .permissions(permissonItems)
                    .checkMutiPermission(new PermissionCallback() {
                        @Override
                        public void onClose() {

                        }

                        @Override
                        public void onFinish() {
                            doNeedPermissionAction(mGameDetail.getStatus(), mGameDetail);
                        }

                        @Override
                        public void onDeny(String permission, int position) {
                            //Util.toast(context,"用户禁止权限申请");
                        }

                        @Override
                        public void onGuarantee(String permission, int position) {

                        }
                    });
        } else {
            Log.e("123456", mGameDetail.getStatus() + "  113");
            if (APPUtil.isAPPInstalled(mContext, mGameDetail.getApkPageName())) {
                mGameDetail.setState("打开");
            } else {
                DownloadTask task = OkDownload.getInstance().getTask(mGameDetail.getId());
                if (task != null)
                    task.register(new GameDownloadListener(mGameDetail.getId(), mGameDetail)).start();
            }
            doNeedPermissionAction(mGameDetail.getStatus(), mGameDetail);
        }

    }

    private void doNeedPermissionAction(String status, ApkDetail mGameDetail) {
        if (status.equals("下载")) {
            startDownload(mGameDetail);
        } else if (status.equals("继续")) {
            DownloadTask task = OkDownload.getInstance().getTask(mGameDetail.getId());
            task.register(new GameDownloadListener(mGameDetail.getId(), mGameDetail)).start();
        } else if (status.equals("安装")) {
            Log.e("123456", status + "  112");
        }
    }

    public void installApk() {
        ApkDetail detail = ApkDetail.getData();
        if (detail.getStatus().equals("安装")) {
            Log.e("123456", "111安装");
            if (TextUtils.isEmpty(detail.getFilePath())) {
                boolean isPermission = true;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    isPermission = mContext.getPackageManager().canRequestPackageInstalls();
                }
                Log.e("123456", "安装1");
                if (isPermission) {
                    DownloadTask task = OkDownload.getInstance().getTask(detail.getId());
                    APPUtil.installApk(mContext, new File(task.progress.filePath));
                    Log.e("123456", "安装2");
                } else {
                    Toast.makeText(mContext, "请授予盒子安装未知来源应用的权限", Toast.LENGTH_SHORT).show();
                    Uri packageURI = Uri.parse("package:" + BuildConfig.APPLICATION_ID);
                    //注意这个是8.0新API
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                    mContext.startActivity(intent);
                    Log.e("123456", "安装3");
                }
            } else
                APPUtil.installApk(mContext, new File(detail.getFilePath()));
        } else if (detail.getStatus().equals("打开")) {
            try {
                APPUtil.openOtherApp(mContext, detail.getApkPageName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.e("123456", "打开");
        } else {
            openBrowser(mContext, detail.getUrl());
            Log.e("123456", "下载");
        }
    }

    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            // 打印Log   ComponentName到底是什么
            Log.d("123456", "componentName = " + componentName.getClassName());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            Log.e("123456", "请下载浏览器");
            Toast.makeText(context.getApplicationContext(), "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
        Log.e("123456", ".......");
    }

    private void startDownload(ApkDetail mGameDetail) {
        //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样
        GetRequest<File> request = OkGo.get(mGameDetail.getUrl());

        //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
        DownloadTask task = OkDownload.request(mGameDetail.getId(), request);//
        task.priority(50)//
                .extra1(mGameDetail)//
                .save()//
                .register(new GameDownloadListener(mGameDetail.getId(), mGameDetail))//
                .start();
    }

    /**
     * 判断当前网络环境：WIFI、移动网络还是无网络状态
     *
     * @return true表示wifi，false 非WiFi 环境
     */
    public static boolean isWiFiConneted(Context ctx) {

        ConnectivityManager conMann = (ConnectivityManager)
                ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mobileNetworkInfo.isConnected()) {
            // Toast.makeText(network_settingActivity.this, "现在是移动网络环境！", Toast.LENGTH_SHORT).show();
        } else if (wifiNetworkInfo.isConnected()) {
            // Toast.makeText(network_settingActivity.this, "现在是WIFI环境！", Toast.LENGTH_SHORT).show();
            return true;
        } else {
            //Toast.makeText(network_settingActivity.this, "现在是没有网络环境！", Toast.LENGTH_SHORT).show();

        }
        return false;
    }

    private class GameDownloadListener extends DownloadListener {

        private final ApkDetail item;

        public GameDownloadListener(Object tag, ApkDetail item) {
            super(tag);
            this.item = item;
        }

        @Override
        public void onStart(Progress progress) {
        }

        @Override
        public void onProgress(Progress progress) {
            updateProgress(progress, item);
        }

        @Override
        public void onError(Progress progress) {
            Throwable throwable = progress.exception;
            if (throwable != null) throwable.printStackTrace();
        }

        @Override
        public void onFinish(File file, Progress progress) {
            updateProgress(progress, item);
            //APPUtil.installApk(mContext, new File(progress.filePath));
        }

        @Override
        public void onRemove(Progress progress) {
        }
    }

    private void updateProgress(Progress progress, ApkDetail item) {
        ApkDetail apk = (ApkDetail) progress.extra1;
        switch (progress.status) {
            case Progress.NONE:
            case Progress.PAUSE:
            case Progress.ERROR:
                item.setState("继续");
                Log.e("123456", "继续");
                break;
            case Progress.WAITING:
                item.setState("等待");
                Log.e("123456", "等待");
                break;
            case Progress.FINISH:

                Log.e("123456", "FINISH");
                if (APPUtil.isAPPInstalled(mContext, item.getApkPageName())) {
                    item.setState("打开");
                } else {
                    if (APPUtil.isApkFileExit(progress.filePath)) {
                        ApkDetail.getData().setFilePath(progress.filePath);
                        item.setState("安装");
                    } else {
                        OkDownload.getInstance().removeTask(apk.getId());
                        item.setState("下载");
                    }
                }
                break;
            case Progress.LOADING:
                item.setState("正在下载");

                Log.e("123456", progress.priority + "");
                break;
            default:
                break;
        }
    }
}
